package com.dragon.pear.modules.trade.common.config;

import com.dragon.common.spring.openapi.ApiGroup;
import com.dragon.common.spring.openapi.ClassTypeChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @author Chris Chan
 * Create On 2025/10/1 下午10:13
 * Use for:
 * Explain:
 */
public class OpenApiUtil2 {
    private static final Logger logger = LoggerFactory.getLogger(OpenApiUtil2.class);

    /**
     * 判断方法是否支持分组
     *
     * @param method
     * @param group
     * @return
     */
    public static synchronized boolean isSupport(Method method, String group) {
        boolean result = false;
        Class<?> controllerClass = method.getDeclaringClass();

        if (ClassTypeChecker.isInterface(controllerClass) && method.isDefault()) {
            // 找到实际的实现类
            Class<?> implementationClass = ImplementationClassFinder.getInstance().findImplementationClass(method);
            if (implementationClass == null) {
                result = false;
            } else {
                controllerClass = implementationClass;
            }
        }

        String foundGroup = findApiGroupFromClass(controllerClass);
        result = group.equals(foundGroup);
        logger.info("判断类 {} 是否支持分组 {}: {}", controllerClass.getName(), group, result);

        return result;
    }

    /**
     * 从类中查找分组标记
     *
     * @param clazz
     * @return
     */
    public static String findApiGroupFromClass(Class<?> clazz) {
        // 优先检查类本身的注解
        if (clazz.isAnnotationPresent(ApiGroup.class)) {
            return clazz.getAnnotation(ApiGroup.class).value();
        }

        // 检查所有接口
        for (Class<?> interfaceClass : clazz.getInterfaces()) {
            if (interfaceClass.isAnnotationPresent(ApiGroup.class)) {
                return interfaceClass.getAnnotation(ApiGroup.class).value();
            }
        }

        // 检查父类
        Class<?> superclass = clazz.getSuperclass();
        if (superclass != null && superclass != Object.class) {
            String superGroup = findApiGroupFromClass(superclass);
            if (superGroup != null) {
                return superGroup;
            }
        }

        return null;
    }
}
